#include "customscroll.h"
#include <QMouseEvent>
#include <QDebug>
#include <QApplication>
#include <QPainter>
#include <QTableWidget>
#include <QHeaderView>
#include <QScrollBar>
#include <QAbstractAnimation>


CustomScroll::CustomScroll(QTableView* table,QWidget *parent) : QWidget(parent)
{
    setAttribute(Qt::WA_TranslucentBackground);

    m_table = table;
    m_scrollBar = table->verticalScrollBar();
    m_table->viewport()->installEventFilter(this);
    m_table->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    animation =  new QPropertyAnimation(m_scrollBar,"value",this);

    connect(&m_scrollTimer,SIGNAL(timeout()),this,SLOT(scrollTimeOut()));
    connect(&m_selectTimer,SIGNAL(timeout()),this,SLOT(selectTimeOut()));

//    this->setMinimumSize(20, 300);
//    this->setMaximumSize(20, 300);
    qDebug()<<"m_table->height()"<<m_table->height()<<"m_table->width()"<<m_table->width();
    this->resize(900,690);
    this->move(900-18,10);            //将滑动条移至最右侧
    this->raise();      //置顶父窗口

    m_srcollH  = m_table->height();
    m_scrollBar->hide();
}

void CustomScroll::selectTimeOut()
{
    m_table->selectRow(m_selectRow);
    m_selectTimer.stop();
    this->update();     //刷新界面
}

void CustomScroll::scrollTimeOut()
{
    this->update();
    if(m_dragFlag == MOUSE_RELEASE_MOVE && animation->state()==QAbstractAnimation::Stopped) //停下来了
    {
        //m_scrollBar->hide();
        m_dragFlag = MOUSE_RELEASE;
        m_scrollTimer.setInterval(1000);
    }
    else
    {
        //m_scrollBar->show();
        if(m_scrollTimer.interval()==1000)
            m_scrollTimer.stop();
    }
}


bool CustomScroll::eventFilter(QObject *obj, QEvent *evt)
{
    static int pressPoint_y   = 0;
    static int dragPoint_y    = -1;
    static qint64 pressMSec ;

    int scrollV_max = m_scrollBar->maximum ();
    int scrollV_min = m_scrollBar->minimum ();

    QMouseEvent *mouse =  dynamic_cast<QMouseEvent *>(evt);
    if(mouse)
    {
        //=================== 首次按下 ===========================
        if( mouse->type() ==QEvent::MouseButtonPress)
        {
            pressMSec = QDateTime::currentDateTime().toMSecsSinceEpoch();     //记录按下的时间
            dragPoint_y  = mouse->pos().y();               //当前坐标
            pressPoint_y = dragPoint_y;                      //按下的位置

            animation->stop();
            m_selectRow = m_table->indexAt(mouse->pos()).row();    //选择当前行
            //qDebug()<<mouse->pos()<<m_selectRow;
            m_selectTimer.start(100);
            m_dragFlag = MOUSE_PRESS;
            return true;
        }
        //======================= 未移动 =============================
        else if(mouse->type() == QEvent::MouseButtonRelease && m_dragFlag == MOUSE_PRESS)
        {
            m_dragFlag = MOUSE_RELEASE;
            if(!m_scrollTimer.isActive())
                m_scrollTimer.start(1000);  //1S后取消滑动条显示
            return true;
        }
        //======================= 鼠标移动 =============================
        else if(mouse->type() == QEvent::MouseButtonRelease && m_dragFlag == MOUSE_PRESS_MOVE)
        {
            dragPoint_y = -1;
            int releasePoint_y = mouse->pos().y();

            int ms= QDateTime::currentDateTime().toMSecsSinceEpoch()-pressMSec;
            int Pixel_per_second=qAbs(releasePoint_y - pressPoint_y)*1000/ms;       //计算每秒像素点

            if(Pixel_per_second < 300 || qAbs(releasePoint_y - pressPoint_y) < 45)
            {
                m_dragFlag = MOUSE_RELEASE;
                if(!m_scrollTimer.isActive())
                    m_scrollTimer.start(1000);  //1S后取消滑动条显示
                return true;
            }
            else
            {
                int moveValue;
                if(ms > 1000)      //滑动的时间太长
                {
                     m_dragFlag = MOUSE_RELEASE;
                     if(!m_scrollTimer.isActive())
                         m_scrollTimer.start(1000);  //1S后取消滑动条显示
                     return true;
                }
                if(releasePoint_y - pressPoint_y > 0)     //向下滑动
                {
                    moveValue = m_scrollBar->value() - Pixel_per_second*0.2*(300/ms);//滑动时间越长,moveValue值越小,因为不是快速滑动
                    if(moveValue < scrollV_min)
                        moveValue = scrollV_min;
                }
                else
                {
                    moveValue = m_scrollBar->value() + Pixel_per_second*0.2*(300/ms);
                    if(moveValue > scrollV_max)
                        moveValue = scrollV_max;
                }
                animation->setDuration(2000-ms);
                animation->setEndValue(moveValue);
                animation->setEasingCurve(QEasingCurve::OutQuart);

                if(!m_scrollTimer.isActive())
                    m_scrollTimer.start(50);  //定时刷新滑动条显示
                animation->start();
                m_dragFlag = MOUSE_RELEASE_MOVE;
            }
            return true;
        }
        //==================== 释放鼠标 ==============================
        else if(mouse->type() == QEvent::MouseMove && (m_dragFlag!= MOUSE_RELEASE) )
        {
            if(m_dragFlag == MOUSE_PRESS)     //首次开始移动
            {
                //判断移动阀值,避免误操作
                if(qAbs(dragPoint_y - mouse->pos().y()) < 4)
                    return true;
                else
                {
                   m_dragFlag = MOUSE_PRESS_MOVE;           //转为移动状态
                   if(m_selectTimer.isActive())
                       m_selectTimer.stop();
                   m_table->clearSelection();               //已经移动了,所以取消之前的选择
                   dragPoint_y = mouse->pos().y();          //获取当前坐标
                   update();                                //重绘滚动条
                   return true;
                }
            }
            //移动值 + 滚动条当前值 = 滑动到的位置
            int moveValue = (dragPoint_y - mouse->pos().y()) + m_scrollBar->value();
            dragPoint_y = mouse->pos().y();
            //添加位置限制
            if(scrollV_min > moveValue) moveValue = scrollV_min;
            if(moveValue > scrollV_max) moveValue = scrollV_max;
            //表格显示到对应位置
            m_scrollBar->setValue(moveValue);
            update();
            return true;
        }
    }
    update();
    return QWidget::eventFilter(obj,evt);
}

void CustomScroll::paintEvent(QPaintEvent *)
{
//    if(m_dragFlag== MOUSE_RELEASE||m_dragFlag== MOUSE_PRESS)
//        return;

    //计算滚动条高度
    int scrolCurrentValue = m_table->verticalScrollBar()->value();
    int scrolMaxValue = m_scrollBar->maximum();
    int scrolLen = ShowRows * m_srcollH / scrolMaxValue;
    if(scrolLen < 50)   scrolLen = 50;
    if(scrolLen > m_srcollH) scrolLen = m_srcollH;
    int scrolPos = scrolCurrentValue * m_table->height() / scrolMaxValue;
    if(scrolPos > (scrolMaxValue - scrolLen))   scrolPos = scrolMaxValue - scrolLen;
    QPainter painter(this);
    painter.setPen(Qt::NoPen);
    painter.setBrush(QColor(200,200,200,140));
    painter.drawRoundedRect(0,scrolPos,SCROL_WIDTH,scrolLen,8,8);
}
